package
{
	import flash.events.Event;
	
	import org.flixel.*;

	public class QuickPlayState extends FlxState
	{
		protected const EASY:int = 0;
		protected const MED:int = 1;
		protected const HARD:int = 2;
		
		private var loadingText:FlxText;
		private var loadingSprite:LoadingIndicator;
		private var cancel:FlxSprite;
		
		public function QuickPlayState()
		{
			loadingText = new FlxText(0, 0, 700, "Loading puzzle ...", false);
			loadingText.setFormat("Courier New", 36, 0xFFFFFF, "center", 1, true);
			loadingText.x = 0;
			loadingText.y = 240;
			
			loadingSprite = new LoadingIndicator(0, 0);
			loadingSprite.x = 312;
			loadingSprite.y = 300;
			this.add(loadingText);
			this.add(loadingSprite);
			var diff:int = Math.round(Math.random() * 2);
			Client.loadAllPuzzlesByDifficultyForFB(diff, loadData);
			Elemental.Log.startDquest(Logging.QUICK_PLAY);
		}
		
		/**
		 * Called when our client has received data from the server.
		 * Removes loading graphic, creates a listing for five puzzles.
		 */
		private function loadData(e:Event):void {
			var maps:String = e.target.data;
			if (maps == "no maps") {
				cancel = new FlxSprite(0,0,Res.cancelButton);
				add(cancel);
			} else {
				var mapArray:Array = maps.split("/");
				var nextRand:int = Math.round(Math.random()*(mapArray.length - 1));
				var chosen:String = mapArray[nextRand];
				var chosenArray:Array = chosen.split(":");
				
				var arrows:Array = String(chosenArray[4]).split(",");
				for (var i:int = 0; i < 4; i++) {
					arrows[i] = int(arrows[i]);
				}
				
				var chickens:Array = String(chosenArray[5]).split(",");
				Elemental.Log.logPlayerMapPlayed(chosenArray[0]);
				var ps:PuzzleSpecification = new PuzzleSpecification(chosenArray[3], chosenArray[7], arrows, chickens, chosenArray[0]);
				FlxG.switchState(new PuzzlePlayingState(ps, false, false, true));
			}
		}
		
		public override function update():void {
			if (FlxG.mouse.justPressed() && cancel.overlapsPoint(FlxG.mouse.screenX, FlxG.mouse.screenY)) {
				FlxG.switchState(new PlayerRoomState());
			}
		}
		
	}
}